package com.example.springboottestgit.controller.main;

import com.alibaba.fastjson.JSONObject;
import com.example.springboottestgit.bean.InstructData;
import com.example.springboottestgit.bean.vo.InputVO;
import com.example.springboottestgit.bean.vo.TextVO;
import com.example.springboottestgit.utils.ExcelExportUtil;
import com.example.springboottestgit.utils.FileUtil;
import com.example.springboottestgit.utils.HttpUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: ZZZ
 */
public class D8099 {
    static List<TextVO> list = new ArrayList<>();
    static List<TextVO> other_question_list = new ArrayList<>();
    static int file_count = 0;
    static String BL = "";
    static String file_path = "C:\\Users\\user\\Desktop\\莆田市财政局(1)\\莆田市财政局\\#";
    static Map<String, String> file_path_name_map = new HashMap<>();
    static String text_path = "C:\\Users\\user\\Desktop\\文件\\#\\#.txt";
    static String excel_path = "C:\\Users\\user\\Desktop\\文件\\#\\#.xlsx";

    public static void main(String[] args) throws IOException {
        filePathAndName(new File("C:\\Users\\user\\Desktop\\莆田市财政局(1)\\莆田市财政局\\"));

        //1-生成问题 txt excel
//        for (int i = 2005; i <= 2023; i++) {
//            file_count = 0;
//            list.clear();
//            BL = i + "";
//            searchFile(new File(file_path.replace("#", BL)));
//            FileUtil.txtWriter(text_path.replace("#", BL), JSONObject.toJSONString(list));
//            export(list, excel_path.replace("#", BL));
//        }


        //2-汇总
       /* String excelFilePath = "C:\\Users\\user\\Desktop\\文件\\#\\#.xlsx";
        for (int i = 2005; i <= 2023; i++) {
            String path = excelFilePath.replace("#", "" + i);
            readExcel(path);
        }
        readExcel("C:\\Users\\user\\Desktop\\文件\\2005-2023-其他问题-完成.xlsx");
        export(list, "C:\\Users\\user\\Desktop\\文件\\2005-2023.xlsx");*/

        //3-问题问答
        int n = 0;
        int m = 0;
        readExcel("C:\\Users\\user\\Desktop\\文件\\2005-2023.xlsx");
        for (TextVO vo : list) {
            n++;
            if (vo.getAnswer().endsWith("。")) {
                m++;
            }
            if (vo.getAnswer().length() > 5) {
                String answer = vo.getAnswer();
                System.out.println(answer);
                if (answer.endsWith("\"")) {
                    answer = answer.substring(0, answer.length() - 1);
                }

                if (answer.startsWith("\"")) {
                    answer = answer.substring(1);

                }
                answer = answer.replace("\\n\\n", "\n");
                answer = answer.replace("\\n", "\n");
                vo.setAnswer(answer);
                System.out.println(vo.getAnswer());
                continue;

            }
            String fileName = vo.getFileName();
            String filePath = file_path_name_map.get(fileName);
            BL = filePath.substring(39, 43);
            fileName = "/" + BL + "/" + fileName;
            System.out.println(fileName);
            System.out.println(vo.getQuestion());
            InputVO inputVO = new InputVO();
            inputVO.setQuestion(vo.getQuestion());
            inputVO.setFileName(fileName);
            String param = JSONObject.toJSONString(inputVO);

            String result = HttpUtils.post("http://192.168.80.35:8099/qwen2/api", param);
            String answer = result;
            if (answer.substring(0, 15).contains("根据") && answer.substring(0, 15).contains(",")) {
                int k = answer.indexOf(",");
                answer = answer.substring(k + 1);
            }
            if (answer.substring(0, 15).contains("根据") && answer.substring(0, 15).contains("，")) {
                int k = answer.indexOf("，");
                answer = answer.substring(k + 1);
            }
            vo.setAnswer(answer);
            System.out.println(answer);


            System.out.println(n);
            System.out.println("==========================");

            // if (n % 5 == 0) {
            //export(list, "C:\\Users\\user\\Desktop\\文件\\2005-2023.xlsx");
            // }
        }
        System.out.println("===========生成excel========");

        //过滤 部分问题需要替换
        List<TextVO> questionList = readExcelList("C:\\Users\\user\\Desktop\\文件\\2005-2023-部分问题手动优化.xlsx");
        Map<String, String> questionMap = new HashMap<>();
        for (TextVO textVO : questionList) {
            questionMap.put(textVO.getFileName(), textVO.getQuestion());
        }
        for (TextVO textVO : list) {
            //部分问题需要替换
            if (questionMap.containsKey(textVO.getFileName())) {
                textVO.setQuestion(questionMap.get(textVO.getFileName()));
            }
        }


        //export(list, "C:\\Users\\user\\Desktop\\文件\\2005-2023-有换行符.xlsx");
        System.out.println("===========生成json========");
        List<InstructData> instructData = new ArrayList<>();
        for (TextVO textVO : list) {
            InstructData instruct = new InstructData();
            instruct.setInstruction(textVO.getQuestion());
            instruct.setInput("");
            instruct.setOutput(textVO.getAnswer());
            instructData.add(instruct);

        }
        FileUtil.txtWriter("C:\\Users\\user\\Desktop\\文件\\2005-2023-json.txt", JSONObject.toJSONString(instructData));
        System.out.println(m);

        for (TextVO textVO : list) {
            String answer = textVO.getAnswer();
            answer = answer.replace("\\n\\n", "\n");
            answer = answer.replace("\\n", "\n");
            textVO.setAnswer(answer);
        }

        //export(list, "C:\\Users\\user\\Desktop\\文件\\2005-2023-无换行符.xlsx");

    }

    public static void searchFile(File dir) throws IOException {
        boolean found = false;//如果没找到要给出回应
        if (dir != null && dir.isDirectory()) {
            File[] files = dir.listFiles();//用数组遍历文件夹中的文件
            if (files != null && files.length > 0) {
                for (File file : files) {
                    if (file.isFile()) {
                        if (file.getName().equals("test.txt")) {
                            continue;
                        }
                        String fileName = file.getName();
                        qwenapi(fileName);

                    } else {
                        searchFile(file);//递归运算
                    }
                }
            }
        } else {
            System.out.println("当前搜索的位置不是文件夹！");
        }
    }

    public static void filePathAndName(File dir) throws IOException {
        boolean found = false;//如果没找到要给出回应
        if (dir != null && dir.isDirectory()) {
            File[] files = dir.listFiles();//用数组遍历文件夹中的文件
            if (files != null && files.length > 0) {
                for (File file : files) {
                    if (file.isFile()) {
                        if (file.getName().equals("test.txt")) {
                            continue;
                        }
                        String fileName = file.getName();
                        String filePath = file.getPath();
                        file_path_name_map.put(fileName, filePath);
                    } else {
                        filePathAndName(file);//递归运算
                    }
                }
            }
        } else {
            System.out.println("当前搜索的位置不是文件夹！");
        }
    }

    public static void qwenapi(String fileName) throws IOException {
        file_count++;
        System.out.println("文件总数：" + file_count);

        LocalDateTime s = LocalDateTime.now();
        String question = "请帮我提出一个可以回答的问题";
        System.out.println(fileName);

        InputVO inputVO = new InputVO();
        inputVO.setQuestion(question);

        inputVO.setFileName("/" + BL + "/" + fileName);
        System.out.println(inputVO.getFileName());

        String param = JSONObject.toJSONString(inputVO);

        String result = HttpUtils.post("http://192.168.80.35:8099/qwen2/api", param);

        System.out.println(result);
        //saveQuestion(result);
        saveQuestion(result, fileName);

        LocalDateTime e = LocalDateTime.now();

        Duration between = Duration.between(s, e);
        System.out.println("耗时：" + between.getSeconds());
        System.out.println();
    }

    public static void saveQuestion(String content, String fileName) {
        TextVO vo = new TextVO();
        vo.setFileName(fileName);
        content = content.replace("：", ":").replace("\\n", "").replace("?", "？");
        String[] split = content.split(":");
        int n = content.substring(0, content.length() > 50 ? 50 : 5).indexOf("问题:");
        int m = content.indexOf("？");

        vo.setContent(content);
        if (n == -1 || m == -1) {

        } else {
            try {
                String question = content.substring(n, m + 1).replace("问题:", "").replace(" ", "").replace(":\n", "");
                //String answer = content.substring(m).replace("回答:", "").replace(" ", "");
                System.out.println("问题：");
                System.out.println(question);
                vo.setQuestion(question);

            } catch (Exception e) {

            }

        }
        list.add(vo);
        System.out.println(BL);


    }

    public static void export(List<TextVO> result, String outputFilePath) {

        List<Map<String, Object>> list = JSONObject.parseObject(JSONObject.toJSONString(result), List.class);

        //表头数组
        String[] lables = new String[]{"文件名", "问题", "回答"};
        //查询数据对应的属性数组
        String[] fields = new String[]{"fileName", "question", "answer",};
        String title = "test.xlsx";
        String headTitle = "指令集";
        //if (result.size() > 1) {
        //title = result.get(0).getName() + "(" + result.get(0).getCode() + ")" + "历史数据.xlsx";
        //headTitle = result.get(0).getName() + "(" + result.get(0).getCode() + ")" + "历史数据";
        //}
        ExcelExportUtil.export(outputFilePath, list, lables, fields, title);

    }

    public static void readExcel(String excelFilePath) {
        try (FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
             Workbook workbook = new XSSFWorkbook(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表
            for (Row row : sheet) { // 迭代每一行
                //System.out.print(row.getCell(0) + "\t");
                //System.out.println(row.getCell(1));
                //System.out.println(row.getCell(1));

                String fileName = row.getCell(0) + "";
                if ("文件名".equals(fileName)) {
                    continue;
                }
                String question = row.getCell(1) + "";
                String answer = row.getCell(2) + "";
                TextVO vo = new TextVO();
                vo.setFileName(fileName);
                vo.setAnswer(answer);
                vo.setQuestion(question);
                list.add(vo);
//                for (Cell cell : row) { // 迭代每一列
//                    // 根据不同数据类型，以字符串形式输出数据
//                    System.out.print(cell.getStringCellValue() + "\t");
//
//                }
//                System.out.println(); // 换行
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<TextVO> readExcelList(String excelFilePath) {
        List<TextVO> list = new ArrayList<>();
        try (FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
             Workbook workbook = new XSSFWorkbook(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表
            for (Row row : sheet) { // 迭代每一行
                //System.out.print(row.getCell(0) + "\t");
                //System.out.println(row.getCell(1));
                //System.out.println(row.getCell(1));

                String fileName = row.getCell(0) + "";
                if ("文件名".equals(fileName)) {
                    continue;
                }
                String question = row.getCell(1) + "";
                String answer = row.getCell(2) + "";
                TextVO vo = new TextVO();
                vo.setFileName(fileName);
                vo.setAnswer(answer);
                vo.setQuestion(question);
                list.add(vo);
//                for (Cell cell : row) { // 迭代每一列
//                    // 根据不同数据类型，以字符串形式输出数据
//                    System.out.print(cell.getStringCellValue() + "\t");
//
//                }
//                System.out.println(); // 换行
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
